<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Passport extends CI_Controller {

	private $admin_dir_name; //后台管理目录名称


	public function __construct()
	{
		parent::__construct();

		//加载前后台公共辅助函数库，后台辅助函数库，URL函数库
		$this->load->helper(array('common_functions_helper', 'admin_functions_helper', 'url')); 

		$this->load->library('session'); //加载session

		$current_uri = $this->uri->segment_array();
		$this->admin_dir_name = $current_uri[1]; //后台管理目录名称

	}


	//显示登录页面
	public function index($msg = '')
	{

		$data['msg'] = $msg;

		//加载验证码
		$this->load->model('bases/verify_code_model');

		$this->verify_code_model->empty_self(); //清空下面的check()函数调用当前函数前产生的遗留数据
		$this->verify_code_model->create_verify_code();

		$data['vvc_id'] = $this->verify_code_model->id;
		$data['vvc_token'] = $this->verify_code_model->token;

		$this->load->view("admin/login.html", $data);
	}


	//验证用户登录
	public function check()
	{

		$error_info = '';

		$username = trim($this->input->post('username', TRUE));
		$password = trim($this->input->post('password', TRUE));

		$this->load->model('bases/verify_code_model');

		$vvc_id = intval($_POST['vvc_id']);
		$vvc_token = trim($this->input->post('vvc_token', true));
		$vvc_code = trim($this->input->post('vvc_code', true));

		if (empty($username) OR empty($password) OR empty($vvc_code) OR empty($vvc_id) OR empty($vvc_token))
		{
			$error_info = '登录信息不完整！';
		}
		elseif (! $this->verify_code_model->check_verify_code($vvc_id, $vvc_token, $vvc_code))
		{
			$error_info = $this->verify_code_model->_error_info;
		}
		else
		{
			//根据用户名获取具有后台管理权限的用户
			$this->load->model('admin/admin_model', 'admin_login');
			$current_admin = $this->admin_login->get_admin_by_username($username);

			//验证用户密码
			if(empty($current_admin) OR $current_admin->password != md5($current_admin->salt . md5($password)))
			{
				$error_info = '用户名或密码错误！';
			}
		}


		//有错误信息时显示登录页面
		if($error_info)
		{
			$this->index($error_info);
		}
		else
		{
			//保存用户id到session
			$this->session->set_userdata('admin_id', $current_admin->id);

			//更新用户登录次数及最后登录时间
			$this->admin_login->id = $current_admin->id;
			$this->admin_login->logins = $current_admin->logins + 1;
			$this->admin_login->last_ip = $this->input->ip_address();
			$this->admin_login->last_time = time();
			$this->admin_login->update();

			redirect("/{$this->admin_dir_name}/"); //跳转到后台首页
		}
	}


	//退出登录
	public function logout()
	{
		//删除admin_id的session值
		$this->session->unset_userdata('admin_id');

		$this->index(); //显示登录页面
	}


}